package com.mall.controller.portal;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.mall.common.Const;
import com.mall.common.ResponseCode;
import com.mall.common.ServerResponse;
import com.mall.pojo.MmallUser;
import com.mall.service.IOrderService;
import com.mall.util.CookieUtil;
import com.mall.util.JsonUtil;
import com.mall.util.RedisPoolUtil;
import com.mysql.fabric.Server;

@Controller
@RequestMapping("/order/")
public class OrderController {
	
	
	@Autowired
	private IOrderService orderService;
	
	
	Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	
	//支付接口
	
	@RequestMapping("/pay.do")
	@ResponseBody
	public ServerResponse pay(Long orderNo, HttpServletRequest request){
		
		//判断是否登录
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if(user == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"need login");
		}
		
		String path = request.getSession().getServletContext().getRealPath("upload");
		
		return orderService.pay(user.getId(), orderNo, path);
	}
	
	
	@RequestMapping("/callback.do")
	@ResponseBody		//回调函数, 当支付过订单后,将商品状态改为已支付.
	public Object callback(HttpServletRequest request){
		
		Map<String,String> params = new HashMap();
		
		Map map = request.getParameterMap();
		for(Iterator iter = map.keySet().iterator();iter.hasNext(); ){
			
			String name = (String)iter.next();
			String[] values = (String[])map.get(name);
			String valueStr = "";
			for(int i =0;i<values.length;i++){
				valueStr = (i == values.length-1)?valueStr + values[i]:valueStr + values[i]+",";
			}
			params.put(name, valueStr);
		}
		
		logger.info("支付宝回调, sign:{},trade_status:{},参数:{}");
		
		//验证回调,很重要!!,验证是不是支付宝发的,并且还要避免重复通知.
		
		// sign_type和sign参数不需要验证,sign在源码中已经验证过了.
		params.remove("sign_type");
		
		try {
			boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
			if(!alipayRSACheckedV2){
				return ServerResponse.createByErrorMessage("非法请求,拒绝!在访问报警");
			}
			
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		
		//验证各种数据
		
		//写业务逻辑
		ServerResponse response = orderService.aliCallback(params);
		if(response.isSuccess()){
			return Const.AlipayCallback.RESPONSE_SUCCESS;
		}
		
		return Const.AlipayCallback.RESPONSE_FAILED;
	}
	
	
	@RequestMapping("/payStatus.do")
	@ResponseBody			//查询订单状态,
	public ServerResponse payStatus(HttpServletRequest request ,Long orderNo){
		
		//判断是否登录
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if(user == null){ 
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"need login");
		}
		
		ServerResponse response = orderService.queryOrderPaySatus(user.getId(), orderNo);
		if(response.isSuccess()){
			return ServerResponse.createBySuccess(true);
		}
		return ServerResponse.createBySuccess(false);
	}
	
	
	//前台 创建订单接口.
	
	@RequestMapping("/createOrder.do") 
	@ResponseBody
	public ServerResponse createOrder(HttpServletRequest request , Integer shippingId){
		
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if( user == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "need_login");
		}
		
		
		return orderService.createOrder(user.getId(),shippingId);
		
	}
	
	//取消订单接口
	
	@RequestMapping("/cancel.do")
	@ResponseBody
	public ServerResponse cancelOrder(HttpServletRequest request,Long orderNo){
		
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if( user == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "need_login");
		}
		
		return orderService.cancelOrder(user.getId(),orderNo);
		
	}
	
	//获取订单的商品信息
	@RequestMapping("/get_order_cart_product.do")
	@ResponseBody
	public ServerResponse get_order_cart_product(HttpServletRequest request){
		
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if( user == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "need_login");
		}
		
		return orderService.getOrderCartProduct(user.getId());
		
	}
	
	@RequestMapping("/detail.do")
	@ResponseBody
	public ServerResponse detail(HttpServletRequest request, Long orderNo){
		
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if( user == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "need_login");
		}
		
		return orderService.getDetail(user.getId(),orderNo);
		
	}
	
	@RequestMapping("/list.do")
	@ResponseBody				//订单List
	public ServerResponse list(HttpServletRequest request, @RequestParam(value="pageNum",defaultValue="1")Integer pageNum,@RequestParam(value="pageSize",defaultValue="10")Integer pageSize){
		
		//MmallUser user = (MmallUser)session.getAttribute(Const.CURRENT_USER);
		String loginToken = CookieUtil.readLoginToken(request);

		if(StringUtils.isEmpty(loginToken)){
			return ServerResponse.createByErrorMessage("用户未登录");
		}
		
		String userStr = RedisPoolUtil.get(loginToken);
		MmallUser user = JsonUtil.string2Obj(userStr, MmallUser.class);
		
		if( user == null){
			return ServerResponse.createByErroerCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "need_login");
		}
		
		return orderService.getOrderList(user.getId(),pageNum,pageSize);
		
	}
	
	
} 
